import re

from django import http
from django.contrib.auth import login, authenticate
from django.db import DatabaseError
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View


from utils.response_code import RETCODE
from .models import User


class RegisterView(View):

    def get(self, request):
        """get请求"""
        return render(request, 'register.html')

    def post(self, request):
        """post请求"""
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')

        # 验证数据
        # 判断参数是否齐全
        if not all([username, password, password2, mobile, allow]):
            return http.HttpResponseBadRequest('缺少必传参数')
        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return http.HttpResponseBadRequest('请输入5-20个字符的用户名')
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseBadRequest('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseBadRequest('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseBadRequest('请输入正确的手机号码')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseBadRequest('请勾选用户协议')

        # 保存注册数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 保持状态
        login(request, user)

        # 响应注册结果
        # return http.HttpResponse('注册成功，重定向到首页')
        return redirect(reverse('index:index'))


class UsernameCountView(View):
    """用户名是否存在"""
    def get(self, request, username):
        """get请求"""
        # 查询数据库用户名数量
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """手机号是否存在"""
    def get(self, request, mobile):
        """get请求"""
        # 查询数据库手机号数量
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class LoginView(View):
    """登录"""
    def get(self, request):
        """get请求"""
        return render(request, 'login.html')

    def post(self, request):
        """post请求"""
        # 获取数据
        username = request.POST.get("username")
        password = request.POST.get("password")
        remembered = request.POST.get("remembered")

        # 验证数据
        # 判断是否缺少参数
        if not all([username, password]):
            # return http.HttpResponseBadRequest("缺少参数")
            return render(request, 'login.html', {'account_errmsg': '缺少参数'})

        # 判断用户名、手机号格式是否正确
        if not re.match(r"^[a-zA-Z0-9_]{5,20}$", username):
            return render(request, 'login.html', {'account_errmsg': '请输入正确的用户名和手机号'})
        # 判断密码格式是否正确
        if not re.match(r"^1[a-zA-Z0-9]{8,20}$", password):
            return render(request, 'login.html', {'account_errmsg': '请输入正确的密码'})

        # 判断用户名，密码是否正确
        user = authenticate(username=username, password=password)
        # 查询到用户
        if user:
            # 保持状态
            login(request, user)
            # 判断是否记住用户
            if remembered == "no":
                request.session.set_expiry(None)
            else:
                request.session.set_expiry(0)

        else:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 登录成功返回主页
        return redirect(reverse('index:index'))
